var interval = null;
var examRecordId = 0;
var loadPageStatus = [];
var questionSaveStatus = {};
$(function () {
   $("body").on('click','#closeWin',function () {//关闭窗口
       layer.closeAll();
       closeIntervalTime();
   }).on('ifChanged','#question-list-box input:radio,#question-list-box input:checkbox',function (event) {//选中单选、多选、判断
       var status = false;
       if(event.target.checked){
           status = true;
       }else{
           if(event.target.type !='radio'){
               status = true;
           }
       }
       if(status){
           saveQuestionRecord(this);
       }
   }).on('blur','#question-list-box input[name=inputBlank]',function () {//填空题
       saveQuestionRecord(this);
   }).on('blur','#question-list-box textarea',function () {//简答题
       saveQuestionRecord(this);
   });

    /**
     * 保存试题记录
     * @param em
     */
    function saveQuestionRecord(em) {
        var root = $($(em).parents('div[data-index]')[0]);
        var index = root.data('index');
        $("#answerSheet li[data-index=\""+index+"\"]").find('a').addClass('btn-info');
        var currentId = root.data('id');
        var saveId = getSaveId(currentId);
        _saveQuestionRecord(currentId,saveId);

    }
});

//关闭定时器
function closeIntervalTime() {
    loadPageStatus = [];
    questionSaveStatus = {};
    if(interval !=null){
        window.clearInterval(interval);
    }
}

/**
 * 验证随堂练习
 * @param courseId 购买的课程ID
 * @param catalogId 目录ID
 */
function checkExercises(courseId,catalogId) {
    $.ajax({
        url: baseloaction +'/web/uc/play/exercises/checkExercises',
        type:'post',
        dataType:'json',
        data:{
            'courseId':courseId,
            'catalogId':catalogId
        },
        success:function (result) {
            if(result.success==true){
                courseCatalogExercises(result.entity);
            }else{
                icModale(0,'',result.message);
            }
        },
        error:function (error) {
            icModale(0,'','系统错误，随堂练习失败');
        }
    });
}

/**
 * 获取随堂练习
 * @param _examRecordId 考试记录ID
 */
function courseCatalogExercises(_examRecordId) {
    closeIntervalTime();
    $.ajax({
        url: baseloaction + '/web/uc/play/exercises/loadExercises',
        data: {'examRecordId': _examRecordId},
        dataType: 'html',
        success: function (html) {
            examRecordId = _examRecordId;
            //停止播放
            stopPlay();
            layer.alert(html, {
                type: 1,
                title: false,
                area: ['1120px', '600px'],
                closeBtn: 0,
                shadeClose: false,
                skin: 'lay_ppComment__wrap',
                success: function (layers) {
                    initPage(layers);
                    //加载答题卡
                    loadExercisesCard(layers,examRecordId);
                    var status = layers.find("#status").val();
                    //加载试题记录
                    loadExercisesQuestionList(layers,{
                        'examRecordId': examRecordId,
                        'status': status,
                        'pageNo': 1
                    });
                }
            });
        }
    });
}

/**
 * 保存随堂练习
 */
function saveExercise() {
    var saveId = getSaveId(0);
    _saveQuestionRecord(0,saveId,function () {
        var courseId = $('#buyCourseId').val();
        var catalogId = $('#playId').val();
        $.ajax({
            url: baseloaction + '/web/uc/play/exercises/saveExercises',
            data: {
                'courseId':courseId,
                'catalogId':catalogId,
                'examRecordId':examRecordId
            },
            dataType: 'json',
            type: 'post',
            success: function (response) {
                if (response.success==true) {
                    closeIntervalTime();
                    layer.closeAll();
                    var button = '';
                    var by = '';
                    if(response.adopt){//是否通过，true通过
                        button = ['下一章节','查看结果'];
                        by = '<span class="c-primary fs24"><i class="fa fa-check"></i> 您已通过本次练习</span>';
                    }else {//false未通过
                        button = ['重新练习','取消'];
                        by = '<span class="c-danger fs24"><i class="fa fa-close"></i> 您未通过本次练习</span>';
                    }
                    var context = '<div class="text-center pt10 mt20">'+by+
                        '<p class="pt10 pl10 pr10"><span class="fs14 c-666">本次练习要求得分率：'+response.scorePercent+'%</span><span class="ml10 fs14 c-666">你的得分率：'+response.userPercent+'%</span></p>'+
                        '</div>';
                    layer.confirm(
                    context,
                    {
                        type: 1,
                        title: '随堂练习提示',
                        area: ['480px', '220px'],
                        closeBtn: 1,
                        offset: 'auto',
                        shadeClose: true,
                        btn : button,
                        btnAlign : 'c'
                    },
                    function(index, layero){//学习下一章
                        if(response.adopt){
                            //继续下一章节
                            var nextCatalog = getNextCatalogId(catalogId);
                            if(nextCatalog!=0){
                                goNextPlay(nextCatalog);
                            }else {
                                icModale(0, '', '已经没有下一章节了');
                            }
                        }else {
                            //继续练习
                            checkExercises(courseId,catalogId);
                        }
                        layer.close(index);
                    },
                    function(index, layero){//查看结果
                        if(response.adopt){
                            var resultText = '您已通过';
                            resultText +=',要求得分率：'+response.scorePercent+'%，您的得分率：'+response.userPercent+"%";
                            //显示结果
                            showExercisesResult(examRecordId,resultText);
                        }
                        layer.close(index);
                    });
                } else {
                    icModale(0, '', response.message);
                }
            },
            error:function (error) {
                icModale(0,'','系统错误，提交随堂练习失败');
            }
        });
    });
}

//执行保存
function _saveQuestionRecord(currentId,saveId,callback) {
    if(saveId > 0){
        var root = $($("#question-list-box>div[data-id='"+saveId+"']")[0]);
        var userAnswer = getAnswerObj(root);
        userAnswer = encodeURIComponent(JSON.stringify(userAnswer));
        saveData("",examRecordId,saveId,userAnswer,function () {
            updateSaveData(saveId,currentId,callback);
        });
    }else{
        updateSaveData(saveId,currentId,callback);
    }
}

/**
 * 获取下一个节点目录的ID
 * @param catalogId 当前获取目录的ID
 */
function getNextCatalogId(catalogId) {
    var allCatalogList = $("#play-catalog a[data-id]");
    var _index = -1;
    $.each(allCatalogList,function (index,em) {
        var _id = $(em).data("id");
        if(_id == catalogId){
            _index = index;
        }
    });
    if(_index > 0 && _index < allCatalogList.length-1){
        var prev = allCatalogList[_index+1];
        return $(prev).data('id');
    }
    return 0;
}

/**
 * 显示练习结果
 * @param _examRecordId 随堂练习考试记录ID
 * @param resultText 随堂练习结果内容
 */
function showExercisesResult(_examRecordId,resultText) {
    $.ajax({
        url:baseloaction +'/web/uc/play/exercises/loadExercises',
        type:'post',
        dataType:'html',
        data:{
            'examRecordId':_examRecordId
        },
        success:function (result) {
            layer.alert(result, {
                type: 1,
                title: false,
                area: ['1120px', '600px'],
                closeBtn: 0,
                shadeClose: false,
                skin: 'lay_ppComment__wrap',
                success: function (layers) {
                    initPage(layers);
                    $("#result-text-box").text(resultText);
                    //加载答题卡
                    loadExercisesCard(layers,_examRecordId);
                    //加载试题记录
                    loadExercisesQuestionList(layers,{
                        'examRecordId': _examRecordId,
                        'status': 2,
                        'pageNo': 1
                    });
                },
                end:function () {
                }
            });
        }
    });
}

/**
 * 初始化页面
 */
function initPage(layers) {
    loadPageStatus = [];
    layers.find('#quitExercises').click(function () {//退出考试
        layer.closeAll();
        closeIntervalTime();
        return false;
    });
    layers.find("#finish").click(function () {//交卷
        saveExercise();
    });
    layers.find('#prev').click(function () {//上一道
        var _index = $('#question-list-box>div[data-index]:visible').data('index');
        switchQuestion(layers,_index,1);
        return false;
    });
    layers.find('#next').click(function () {//下一道
        var _index = $('#question-list-box>div[data-index]:visible').data('index');
        switchQuestion(layers,_index,2);
        return false;
    });
}


/**
 * 切换试题
 * @param index 下标
 * @param type 类型，1上一道，2下一道
 */
function switchQuestion(layers,index,type) {
    if(type==1){//上一道
        index = parseInt(index) - 1;
        if(index <= 0 ){
            icModale(0, '', '当前为第一道试题');
            return;
        }
    }
    if(type==2){//下一道
        var questionList = $('#question-list-box>div[data-index]');
        var len = questionList.length;
        index = parseInt(index) + 1;
        if(index > len){
            icModale(0, '', '已是最后一道试题');
            return;
        }
    }
    //加载页面数据
    loadPageData(layers,index);
}

/**
 * 加载随堂练习试题数据列表
 * @param layers 弹框的对象
 * @param obj 参数对象
 */
function loadExercisesQuestionList(layers,obj) {
    if(loadPageStatus.indexOf(obj.pageNo) ==-1){
        loadPageStatus.push(obj.pageNo);
        $.ajax({
            url: baseloaction +'/web/uc/play/exercises/loadExercisesQuestionList',
            type:'post',
            dataType:'html',
            data:{
                'examRecordId':obj.examRecordId,
                'status':obj.status,
                'currentPage':obj.pageNo
            },
            success:function (html) {
                if(obj.pageNo==1){
                    layers.find('#question-list-box').append(html);
                }else{
                    var pageEm = layers.find("div[data-no="+obj.pageNo+"]")[0];
                    $(html).insertBefore($(pageEm));
                    layers.find(".temporary-box[data-no="+obj.pageNo+"]").remove();
                }
                //单选框/多选框样式
                layers.find('.i-checks').iCheck({
                    checkboxClass: 'icheckbox_square-green',
                    radioClass: 'iradio_square-green'
                });
                if($.isFunction(obj.callback)){
                    obj.callback();
                }
            },
            error:function (error) {
                icModale(0,'','系统错误，加载随堂练习试题失败');
            }
        });
    }else{
        if($.isFunction(obj.callback)){
            obj.callback();
        }
    }
}

/**
 * 加载答题卡数据
 * @param layers 弹框对象
 * @param examRecordId 考试记录ID
 */
function loadExercisesCard(layers,examRecordId) {
    $.ajax({
        url: baseloaction +'/web/uc/play/exercises/loadExercisesCard',
        type:'post',
        dataType:'html',
        data:{
            'examRecordId':examRecordId
        },
        success:function (html) {
            layers.find("#answerSheet").html(html);
            var cardList = $("#answerSheet>li>a");
            $.each(cardList,function (index,em) {
                var id = $(em).data('id');
                questionSaveStatus['qr'+id]={'id':id,'status':false};
            });
            layers.find("#answerSheet>li").click(function () {//点击答题卡
                var index = $(this).data('index');
                //加载页面数据
                loadPageData(layers,index);
            });
        },
        error:function (error) {
            icModale(0,'','系统错误，加载随堂练习答题卡失败');
        }
    });
}


/**
 * 加载页面数据
 * @param layers 弹框对象
 * @param index 试题下标
 */
function loadPageData(layers,index) {
    $("#question-list-box>div").hide();
    var pageEm = $("#question-list-box>div[data-index="+index+"]")[0];
    var status = layers.find("#status").val();
    var pageNo = $(pageEm).data('no');
    loadExercisesQuestionList(layers,{
        'examRecordId':examRecordId,
        'status':status,
        'pageNo':pageNo,
        callback:function () {
            $("#question-list-box>div[data-index="+index+"]").show();
        }
    });
    layers.find('#answerSheet li[data-index="' + index + '"]').addClass('active').siblings().removeClass('active');
}


/**
 * 更新保存后的数据
 * @param saveId
 * @param currentId
 */
function updateSaveData(saveId,currentId,callback) {
    if(currentId > 0){
        questionSaveStatus['qr'+currentId] = {'id':currentId,'status':true};
    }
    if(saveId > 0){
        questionSaveStatus['qr'+saveId] = {'id':saveId,'status':false};
    }
    if($.isFunction(callback)){
        callback();
    }
}

/**
 * 获取要保存的试题记录ID
 * @param currentId
 * @returns {number}
 */
function getSaveId(currentId) {
    var status = true;
    var saveId = 0;
    $.each(questionSaveStatus,function (index,obj) {
        if(obj.status==true && status==true && obj.id != currentId){
            saveId = obj.id;
            status = false;
        }
    });
    return saveId;
}